/**
 * 基于网络状况的自适应加载
 */
export class AdaptiveLoader {
  constructor() {
    this.networkInfo = {
      effectiveType: '4g',
      saveData: false,
      downlink: 10
    };
    this.listeners = new Set();

    if (navigator.connection) {
      this.updateNetworkInfo(navigator.connection);
      navigator.connection.addEventListener('change', () => {
        this.updateNetworkInfo(navigator.connection);
      });
    }
  }

  updateNetworkInfo(connection) {
    this.networkInfo = {
      effectiveType: connection.effectiveType || '4g',
      saveData: connection.saveData || false,
      downlink: connection.downlink || 10,
      rtt: connection.rtt || 50
    };
    this.notifyListeners();
  }

  onNetworkChange(callback) {
    this.listeners.add(callback);
    return () => this.listeners.delete(callback);
  }

  notifyListeners() {
    this.listeners.forEach(cb => cb(this.networkInfo));
  }

  shouldLoadLightResource() {
    return this.networkInfo.effectiveType.includes('2g') || this.networkInfo.saveData;
  }

  getImageQuality() {
    if (this.networkInfo.effectiveType.includes('2g')) return 'low';
    if (this.networkInfo.effectiveType.includes('3g')) return 'medium';
    return 'high';
  }

  loadScript(url, isCritical = false) {
    if (!isCritical && this.shouldLoadLightResource()) {
      return Promise.resolve(null);
    }

    return new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = url;
      script.onload = resolve;
      script.onerror = reject;
      document.body.appendChild(script);
    });
  }
}

/**
 * React Hook封装自适应加载
 */
export const useAdaptiveLoader = () => {
  const [loader] = useState(() => new AdaptiveLoader());
  const [network, setNetwork] = useState(loader.networkInfo);

  useEffect(() => {
    return loader.onNetworkChange(setNetwork);
  }, [loader]);

  return {
    network,
    shouldLoadLightResource: loader.shouldLoadLightResource,
    getImageQuality: loader.getImageQuality,
    loadScript: loader.loadScript
  };
};

/**
 * 自适应图片组件
 */
export const AdaptiveImage = ({ src, lowQualitySrc, alt = '', ...props }) => {
  const { getImageQuality } = useAdaptiveLoader();
  const quality = getImageQuality();
  const imageSrc = quality === 'low' && lowQualitySrc ? lowQualitySrc : src;

  return <img src={imageSrc} alt={alt} loading="lazy" {...props} />;
};
